首先,区分空串和null串
1、 空串""是长度为0的字符串,它有自己的串长度(0)和内容(空),判断一个字符串为空的方法:
if (str.length() == 0);或if (str.equals(""));
2、 null串表示目前没有任何对象与该变量关联,检查一个字符串是否为null的方法:
if (str == null);
3、检查一个字符串既不是null串也不是空串,多用以下方法判断:
if (str != null && str.length() != 0);
注意:要先检查str不为null,否则在一个null值上调length()方法会出现错误。
4、使用StringUtils工具类,判断不为null也不是空,如下:
if (StringUtils.isNotBlank(str))
isNotEmpty(str)等价于 str != null && str.length > 0
isNotBlank(str) 等价于 str != null && str.length > 0 && str.trim().length > 0
同理
isEmpty 等价于 str == null || str.length == 0
isBlank 等价于 str == null || str.length == 0 || str.trim().length == 0
str.length > 0 && str.trim().length > 0 ---> str.length > 0
1.public static boolean isBlank(String str)
在校验一个String类型的变量是否为空时,通常存在5种情况
1.是否为 null
2.是否为 ""
3.是否为空字符串(引号中间有空格) 如: " "。
4.制表符、换行符、换页符和回车
5.空白
例子:
StringUtils的isBlank()方法可以一次性校验这五种情况,返回值都是true,否则为false
示例:
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("\t \n \f \r") = true //对于制表符、换行符、换页符和回车
StringUtils.isBlank()=true //均识为空白符
StringUtils.isBlank("\") = false //"\b"为单词边界
StringUtils.isBlank("fff") = false
StringUtils.isBlank("ffff ") = false
2. public static boolean isEmpty(String str)
判断某字符串是否为空,为空的标准是 str==null 或 str.length()==0
下面是 StringUtils 判断是否为空的示例:
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false //注意在 StringUtils 中空格作非空处理
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("fff") = false
StringUtils.isEmpty(" fff ") = false
「三年博客,如果觉得我的文章对您有用,请帮助本站成长」
共有 0 - java判断字符串不为空和null的方法